package com.smartyu.util;


import com.smartyu.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：qianyu
 * @date ：Created in 2020/5/29 22:40
 * @modified By：
 */
@Component
public class HtmlParseUtil {

   public static void main(String[] args) throws IOException {


       String keyWords="数学";
       new HtmlParseUtil().parseJD(keyWords).forEach(System.out::println);


   }


   public List<Content> parseJD(String keyWords) throws IOException {
       String url="https://search.jd.com/Search?keyword="+keyWords;
       Document document = Jsoup.parse(new URL(url), 3000);

       Element element = document.getElementById("J_goodsList");

       Elements li = element.getElementsByTag("li");

       ArrayList<Content> goodList = new ArrayList<>();
       for (Element el : li) {
           String img = el.getElementsByTag("img").eq(0).attr("src");
           String p_price = el.getElementsByClass("p-price").eq(0).text();
           String title = el.getElementsByClass("p-name").eq(0).text();

           Content content=new Content();
           content.setTitle(title);
           content.setPrice(p_price);
           content.setImg(img);

           goodList.add(content);
       }

       return goodList;
   }


}
